<script setup>
import {
  addClassApi,
  classListQueryApi,
  deleteClassApi,
  editClassInfoApi,
  getClassApi,
  uploadClassExcelApi
} from '@/api/baseData'
import { updateUserStatusApi } from '@/api/user'
import Form from '@/components/User/Form.vue'
import FormAdd from '@/components/common/formAdd.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/common/table.vue'
import { useUserStore } from '@/stores/user'
import { dayFormat } from '@/utils/common/dayjs'
import { bus } from '@/utils/common/mitt'
import { showStatusMessage } from '@/utils/common/showMessage'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { utils, writeFileXLSX, read } from 'xlsx'
// import XLSX from 'xlsx';
// 获取年份
const yearData = new Date().getFullYear()
const router = useRouter()
// 表单数据
const formData = ref({
  college: '',
  major: '',
  class: ''
})

let formModel = [
  {
    prop: 'college',
    label: '学院',
    type: 'selectCollege'
  },
  {
    prop: 'major',
    label: '专业',
    type: 'selectMajor'
  },
  {
    prop: 'class',
    label: '班级',
    type: 'selectClass'
  }
]

const btnOpt = [
  {
    name: '查询',
    btnType: '',
    prop: 'query'
  },
  {
    name: '新增',
    btnType: 'success',
    prop: 'add'
  },
  {
    name: '导出',
    btnType: 'warning',
    prop: 'output'
  },
  {
    name: '重置',
    btnType: 'info',
    prop: 'reset'
  },
  {
    name: '导入',
    btnType: 'info',
    prop: 'import'
  }
]

// 对话框的显示隐藏
const dialogFormVisible = ref(false)
// 注册学院表单数据
const form = ref({
  college: '',
  major: '',
  class: '',
  instructor: {
    name: '',
    teacherNumber: ''
  }
})

const studentFormOpt = [
  {
    label: '学院',
    type: 'selectCollege',
    prop: 'college'
  },
  {
    label: '专业',
    type: 'selectMajor',
    prop: 'major'
  },
  {
    label: '班级',
    type: 'input',
    prop: 'class'
  },
  {
    label: '班级辅导员',
    type: 'instructorSelect',
    prop: 'instructor'
  }
]
const btnOptStudent = [
  {
    name: '取消',
    btnType: '',
    prop: 'cancel'
  },
  {
    name: '确定',
    btnType: 'success',
    prop: 'confirm'
  }
]
const formRef = ref(null)
const pagizationToatl = ref(null)

// 列表数据
const tableData = ref([])
const columns = [
  {
    prop: 'college',
    label: '学院'
  },
  {
    prop: 'major',
    label: '专业'
  },
  {
    prop: 'class',
    label: '班级'
  },
  {
    prop: 'instructor',
    label: '班级辅导员'
  },
  {
    prop: 'instructorAccount',
    label: '教职工号'
  },

  {
    prop: 'count',
    label: '班级人数'
  }
]
const options = [
  {
    label: '编辑',
    type: 'warning',
    prop: 'edit'
  },

  {
    label: '删除',
    type: 'danger',
    prop: 'delete'
  }
]
const userStore = useUserStore()
/**
 * 获取表格数据
 */
async function getCollegeData(data) {
  let res=null
  if (userStore.userInfo.college === '*') {
    res = await classListQueryApi(data)
  } else {
    res = await classListQueryApi({ ...data, college: userStore.userInfo.college })
  } 
  tableData.value = res.data
  pagizationToatl.value = res.total
}
getCollegeData()
const pagizationRef = ref(null)
const selectFormRef = ref(null)
/**
 * 点击重置按钮
 */
function reset() {
  getCollegeData()
  pagizationRef.value.reset()
  selectFormRef.value.reset()
}
/**
 * 表单按钮添加事件
 */
function addForm() {
  dialogFormVisible.value = true
}
/**
 * 对话框取消事件
 */
function cancel() {
  formRef.value.reset()
  dialogFormVisible.value = false
}
const editorId = ref(null)
// 表格编辑事件
function handletTableEdit(data) {
  editorId.value = data.id
  form.value = {
    college: data.college,
    major: data.major,
    class: data.class,
    instructor: { name: data.instructor, teacherNumber: data.instructorAccount }
  }
  dialogFormVisible.value = true
}
/**
 * 对话框确定事件
 */
async function confirm(data) {
  const create_time = dayFormat(new Date())
  let res = null
  if (editorId.value != null) {
    res = await editClassInfoApi({ ...data, create_time, editorId: editorId.value })
  } else {
    res = await addClassApi({ ...data, create_time })
  }
  showStatusMessage(res)
  dialogFormVisible.value = false
  editorId.value = null
  form.value = {
    college: '',
    major: '',
    class: '',
    instructor: {
      name: '',
      teacherNumber: ''
    }
  }
  getCollegeData()
}
async function importExcel(data) {
  console.log(data)
}
/**
 * 表单查询事件
 * @param {Object} data 查询条件
 */
async function query(data) {
  let res=null
  if (userStore.userInfo.college === '*') {
    res = await classListQueryApi(data)
  } else {
    res = await classListQueryApi({ ...data, college: userStore.userInfo.college })
  }
  showStatusMessage(res)
  tableData.value = res.data
  pagizationToatl.value = res.total
}
// 导出excel
async function exportToExcel() {
  // 获取要导出的业务数据
  const res = await getClassApi()
  const data = res.data
  console.log(data)

  // 表头中文字段value
  const tableHeaderValues = ['序号', '学院', '专业', '班级', '班级辅导员', '教职工号', '班级人数']
  // 以excel表格的顺序调整后端数据
  const sheetData = data.map((item, index) => {
    let obj = {}
    obj = {
      index: index + 1,
      college: item.college,
      major: item.major,
      class: item.class,
      instructor: item.instructor,
      instructorAccount: item.instructorAccount,
      count: item.count
    }
    return obj
  })
  // 创建一个工作表
  const worksheet = utils.json_to_sheet(sheetData)
  // 创建一个新的工作簿
  const workbook = utils.book_new()
  // 把工作表添加到工作簿
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
  writeFileXLSX(workbook, `${dayFormat(new Date())}导出数据.xlsx`)
}

/**
 * 表单按钮点击事件
 * @param type 操作类型
 * @param data 表单数据
 */
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'add':
      addForm()
      break
    case 'output':
      exportToExcel()
      break
    case 'cancel':
      cancel()
      break
    case 'confirm':
      confirm(data)
      break
    case 'reset':
      reset(data)
      break
    case 'import':
      handleUpload(data)
      break

    default:
      break
  }
}

/**
 * 修改账号是否被禁用事件
 * @param data 0|1禁用状态
 */
async function handletTableSwitch(data) {
  const res = await updateUserStatusApi({ account: data.account, status: data.status })
  showStatusMessage(res)
}
// 表格删除事件
async function handletTableDelete(data) {
  const res = await deleteClassApi(data)
  showStatusMessage(res)
  getCollegeData()
  bus.emit('delete')
}

/**
 * 表格的操作事件
 * @param {Object} data  操作行的数据
 * @param {String} type 操作类型-’edit’-‘delete’
 */
function handleTable(data, type) {
  // console.log(data, type)
  switch (type) {
    // 修改账号是否被禁用
    case 'switch':
      handletTableSwitch(data)
      break
    case 'delete':
      handletTableDelete(data)
      break
    case 'edit':
      handletTableEdit(data)
      break

    default:
      break
  }
}
// 分页器条数发生变化
function handleSizeChange(val) {
  console.log('条数发生变化')
  getCollegeData({ size: val })
  pagizationRef.value.reset()
}
// 分页器页数发生变化
function handleCurrentChange(page, size) {
  console.log('页数发生变化')
  console.log(page, size)

  getCollegeData({ page, size })
}
/**
 * 处理文件上传功能
 * 该函数通过FileReader读取用户上传的文件，并将其转换为JSON格式的数据，以便进一步处理
 * @param {Event} e 文件上传事件，包含上传的文件信息
 */
async function handleUpload(e) {
  const res = await uploadClassExcelApi({ jsonData: e, create_time: dayFormat(new Date()) })
  showStatusMessage(res)
  getCollegeData()
}
</script>

<template>
  <div class="user-wrapper">
    <div class="user-content">
      <Form
        :data="formData"
        :formOpt="formModel"
        :btnOpt="btnOpt"
        @handleForm="handleForm"
        ref="selectFormRef"
      ></Form>
      <!-- 表格 -->
      <Table
        :tableData="tableData"
        :columns="columns"
        :options="options"
        @handleTable="handleTable"
      >
        <template #firstColumn>
          <el-table-column type="index" label="序号" width="100" align="center" />
        </template>
      </Table>
      <!-- 分页 -->
      <Pagization
        ref="pagizationRef"
        :total="pagizationToatl"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></Pagization>
    </div>
    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="新增班级"
      width="500"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <FormAdd
        ref="formRef"
        :data="form"
        :formOpt="studentFormOpt"
        :btnOpt="btnOptStudent"
        @handleForm="handleForm"
      ></FormAdd>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: start;
  .user-content {
    width: 100%;
    padding: 30px 50px;
    text-align: left;
    overflow: auto;
  }
}
</style>
